import { InboxOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import type { RcFile } from 'antd/es/upload';
import Dragger from 'antd/es/upload/Dragger';

import { getHeaders } from '@/utils/ReqInstance/axios';

import { Messages } from '../Messages/Messages';
import styles from './styles.module.less';

type props = {
  setFile: (file: RcFile | null) => void;
};

export default function FileUploader({ setFile }: props) {
  const getFileExtension = (filename: string) => {
    if (!filename) return ''; // 文件名为空的情况
    const parts = filename.split('.');
    if (!parts || parts.length === 0 || (parts[0] === '' && parts.length === 1)) {
      return ''; // 没有扩展名或隐藏文件
    }
    return parts.pop()?.toLowerCase() || ''; // 获取扩展名并转换为小写
  };

  const props: UploadProps = {
    name: 'file',
    maxCount: 1,
    accept: '.hust',
    headers: {
      ...getHeaders(),
      'accept-encoding': 'zh-CN,zh;q=0.9',
      'accept-language': 'gzip, deflate, brz',
    },
    beforeUpload: (file: RcFile) => {
      const allowedExtensions = ['hust'];
      const fileExtension = getFileExtension(file.name);
      const isAllowedExtension = allowedExtensions.includes(fileExtension);

      if (!isAllowedExtension) {
        Messages.error('请上传hust文件');
        return false;
      }
      const size = file.size;
      if (size === 0) {
        Messages.error('文件大小不能为0');
        return false;
      }

      if (size > 10 * 1024 * 1024) {
        Messages.error('上传文件限制在10MB以内');
        return false;
      }
      setFile(file); // Save the file to the state
      return false; // Prevent auto upload
    },
  };
  return (
    <span>
      <Dragger {...props}>
        <p>
          <InboxOutlined />
        </p>
        <p className={styles.UploadWrapper}>将文件拖到此处或点击上传</p>
        <p className={styles.UploadHint}>支持上传hust格式文件。</p>
      </Dragger>
    </span>
  );
}
